var express = require('express');
var router = express.Router();
const { WebSocketServer } = require('ws');
const OpenAI = require('openai');
const path = require('path');
require('dotenv').config();

// Initialize OpenAI
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  baseURL: "https://xiaoai.plus/v1"
});

// WebSocket server setup
let wss;
function setupWebSocket(server) {
  wss = new WebSocketServer({ server: server, path: '/ws' });
  
  // Client management
  const clients = [];
  let nextId = 1;

  wss.on('connection', (ws) => {
    const clientId = `client_${nextId++}`;
    console.log(`New client connected: ${clientId}`);

    ws.on('message', (message) => {
      try {
        const data = JSON.parse(message.toString());
        
        if (data.type === 'register') {
          // Register client
          clients.push({
            ws,
            role: data.role,
            id: clientId
          });
          console.log(`Client registered as ${data.role}: ${clientId}`);
        } else if (data.type === 'message') {
          // Forward message
          const sender = clients.find(client => client.ws === ws);
          if (!sender) return;

          // If sender is customer, send to all agents
          // If sender is agent, send to all customers
          const targetRole = sender.role === 'agent' ? 'customer' : 'agent';
          clients
            .filter(client => client.role === targetRole)
            .forEach(client => {
              client.ws.send(JSON.stringify({
                type: 'message',
                content: data.content,
                from: sender.id
              }));
            });
        }
      } catch (error) {
        console.error('Error processing message:', error);
      }
    });

    ws.on('close', () => {
      // Remove disconnected client
      const index = clients.findIndex(client => client.ws === ws);
      if (index !== -1) {
        console.log(`Client disconnected: ${clients[index].id}`);
        clients.splice(index, 1);
      }
    });
  });
}

// ChatGPT API route
router.get('/chat', async (req, res) => {
  const prompt = req.query.prompt;
  if (!prompt) {
    res.status(400).json({ error: 'Missing prompt parameter' });
    return;
  }

  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  try {
    const stream = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: prompt }],
      stream: true,
    });

    for await (const part of stream) {
      const formattedResponse = {
        choices: [{
          delta: {
            content: part.choices[0]?.delta?.content || ''
          }
        }]
      };
      res.write(`data: ${JSON.stringify(formattedResponse)}\n\n`);
    }
    res.write('data: [DONE]\n\n');
  } catch (error) {
    console.error('Error:', error);
    const errorResponse = {
      error: true,
      message: 'An error occurred while processing your request'
    };
    res.write(`data: ${JSON.stringify(errorResponse)}\n\n`);
    res.write('data: [DONE]\n\n');
  }
  res.end();
});

// Admin page route
router.get('/admin', (req, res) => {
  res.sendFile(path.join(process.cwd(), 'admin.html'));
});

// Basic test route
router.get('/test', async (req, res) => {
  try {
    const completion = await openai.chat.completions.create({
      messages: [{ role: 'user', content: 'How are you today?' }],
      model: 'gpt-3.5-turbo',
      max_tokens: 20,
    });
    res.json(completion.choices[0]);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Export both the router and the WebSocket setup function
module.exports = {
  router: router,
  setupWebSocket: setupWebSocket
};
